$(function(){
	
	var studentUrl = '/course-work-management/student';
	var teacherUrl = '/course-work-management/teacher';
	
	// Tooltip
	$('[data-tooltip="true"]').tooltip();
	
	// Load course and its teacher works for the first time
	loadCoursesData().done(function(){
		if($('#courses select').find('option')) {
			loadTeacherWorksData($('#courses select:first-child').val());
		}
	});
	
	// Reset form after hidding the modal
	$('.modal').on('hidden.bs.modal', function() {
        if($(this).find('form')) {
            $(this).find('form')[0].reset();
        }
        if($(this).find('.alert')) {
        	$(this).find('.alert').alert('close');
        }
    });
	
	// Show a modal and add a new course
	$('#addCourseModal button:last').on('click', function(){
		if ($('#addCourseModal input').val().length == 0) {
			$('#addCourseModal .modal-body').prepend(createAlert('danger', 'Error', '课程名称不为空！'));
		} else {
			var param = {
					courseName : $('#addCourseModal input').val(),
					courseNo : $('#addCourseModal option:selected').text()
			};
			$.post(studentUrl + '/course/action/add', param, function(result){
				if(result.succeeded){
					$('#addCourseModal').modal('hide');
					loadCoursesData();
				} else {
					$('#addCourseModal .modal-body').prepend(createAlert('danger', 'Error', result.message));
				}
			});
		}
	});
	
	// Delete course and alert message
	$('#deleteCourseModal button:last').on('click', function(){
		$.ajax({
			url: studentUrl + '/course/id/' + $('#courses select option:selected').val(),
			type: 'DELETE',
		}).done(function(result){
			$('#deleteCourseModal').modal('hide');
			if(result.succeeded){
				loadCoursesData();
			} else {
				$('.container:eq(1)').prepend(createAlert('danger', 'Error', result.message));
			}
		});
	});
	
	// Change course option and get teacher works of this course
	$('#courses select').on('change', function(){
		// Reset teacher work and student works panel
		resetWorkPanel();
		loadTeacherWorksData($('#courses select option:selected').val())
	});

	// change the file's name when selecting file
	$('#addStudentWorkModal input[type="file"]').on('change', function(e) {
        var filename = $(e.currentTarget).val().replace(/^.*\\/, "");
        $('#addStudentWorkModal input[type="text"]').val(filename);
    });
	
	// Show a modal and add a new teacher work
    $('#addStudentWorkModal .modal-footer button:last').on('click', function() {
    	if ($('#addStudentWorkModal input[type="text"]').val().length == 0) {
    		$('#addStudentWorkModal .modal-body').prepend(createAlert('danger', 'Error', '附件不为空！'));
    	} else {
    		var formData = new FormData();
    		formData.append('attachment', $('#addStudentWorkModal input[type="file"]')[0].files[0]);
    		$.ajax({
    			url: studentUrl + '/student-work/id/' + $('#workPanelHeading').data('id') + '/action/submit',
    			type: 'POST',
    			data: formData,
    			contentType: false,
    			cache: false,
    			processData: false
    		}).done(function(result) {
    			if(result.succeeded) {
    				$('#addStudentWorkModal').modal('hide');
    				refreshStudentWorkData($('#workPanelHeading').data('id'));
    			} else {
    				$('#addStudentWorkModal .modal-body').prepend(createAlert('danger', 'Error', result.message));
    			}
    		});
    	}
    }); 
	
	// Refresh course data
	function loadCoursesData() {
		return $.get(studentUrl + '/courses', function(data){
				   $('#courses select').empty();
				   $.each(data, function(index){
					   $('#courses select').append('<option value="' + data[index].id + '">' + data[index].courseName + '_' + data[index].courseNo +'</option>');
				   });
			   });
	}
	
	// Refresh teacher works data
	function loadTeacherWorksData(courseId) {
		var teacherWorksDiv = $("#teacherWorks .list-group");
		$.get(teacherUrl + '/course/id/' + courseId + '/teacher-works', function(data){
			teacherWorksDiv.empty();
			$.each(data, function(index){
				teacherWorksDiv.append('<a href="" class="list-group-item" style="margin-bottom: 5px;" data-id="' + data[index].id + '">' + data[index].title + '</a>');
			});
		}).done(function(){
			if(teacherWorksDiv.find('a')) {
				teacherWorksDiv.find('a').on('click', function(e){
				   	e.preventDefault();
				   	loadCurrentTeacherWorkAndStudentWorkData($(e.target).data('id'));
				});
			}
		});
	}
	
	// Refresh current teacher work detail data and current student works
	function loadCurrentTeacherWorkAndStudentWorkData(teacherWorkId){
		// Get teacher work
		$.get(teacherUrl + '/teacher-work/id/' + teacherWorkId, function(data){
    		$('#workPanelHeading li:eq(0)').text($('#courses select option:selected').text());
    		$('#workPanelHeading li:eq(1)').text(data.title);
    		$('#workPanelHeading button').show();
    		$('#workPanelContent h3:eq(0)').show();
    		$('#workPanelContent table:eq(0)').html(
				'<tbody>' + 
					'<tr><th class="col-md-2">标题:</th>' + '<th class="col-md-10">' + data.title + '</th></tr>' +
					'<tr><th>内容:</th>' + '<th><pre style="max-width: 570px; overflow: auto;">' + data.content + '</pre></th></tr>' +
					'<tr><th>发布日期:</th>' + '<th>' + getFormattedTime(data.informDate) + '</th></tr>' +
					'<tr><th>上交期限:</th>' + '<th>' +getFormattedTime(data.deadline) + '</th></tr>' +
					'<tr><th>附件:</th>' + '<th><a href="' + teacherUrl + '/teacher-work/id/' + data.id + '/attachment">' +  getFileName(data.filePath) + '</a></th></tr>' +
				'</tbody>'
    		);
    	});
    	// Get student work
    	$.get(studentUrl + '/teacher-work/id/' + teacherWorkId + '/student-work', function(data){
    		$('#workPanelHeading').data('id', data.id);
    		$('#workPanelContent h3:eq(1)').show();
    		if(data.submitted) {
    			$('#workPanelContent table:eq(1)').html(
    	    			'<thead><tr><th>作业附件</th><th>提交日期</th><th>成绩</th></tr></thead>' +
    					'<tbody>' + 
    						'<tr>' + 
    							'<td>' +
    								'<a href="' + teacherUrl + '/student-work/id/' + data.id + '/attachment">' + getFileName(data.filePath) + '</a>' +
    							'</td>' + 
    							'<td>' + getFormattedTime(data.submitDate) + '</td>' + 
    							'<td>' + data.score + '</td>' +
    						'</tr>' +
    					'</tbody>'
    	    		);
    		} else {
    			$('#workPanelContent table:eq(1)').html(
    	    			'<thead><tr><th>作业附件</th><th>提交日期</th><th>成绩</th></tr></thead>'
    	    		);
    		}
    	});
	}
	
	// Refresh student work after submit
	function refreshStudentWorkData(studentId) {
		$.get(studentUrl + '/student-work/id/' + studentId, function(data){
    		$('#workPanelHeading').data('id', data.id);
    		$('#workPanelContent table:eq(1)').html(
    			'<thead><tr><th>作业附件</th><th>提交日期</th><th>成绩</th></tr></thead>' +
				'<tbody>' + 
					'<tr>' + 
						'<td>' +
							'<a href="' + teacherUrl + '/student-work/id/' + data.id + '/attachment">' + getFileName(data.filePath) + '</a>' +
						'</td>' + 
						'<td>' + getFormattedTime(data.submitDate) + '</td>' + 
						'<td>' + data.score + '</td>' +
					'</tr>' +
				'</tbody>'
    		);
    	});
	}
	
	// Reset teacher work and student works panel
	function resetWorkPanel() {
		$('#workPanelHeading li:eq(0)').text('');
		$('#workPanelHeading li:eq(1)').text('');
		$('#workPanelHeading').data('id', '');
		$('#workPanelHeading button').hide();
		$('#workPanelContent h3').each(function(){
			$(this).hide();
		});
		$('#workPanelContent table').each(function(){
			$(this).hide();
		});
	}
	
	// Format time
	function getFormattedTime(time) {
		var date = new Date();
		date.setTime(time);
		return date.format('yyyy-mm-dd  HH:mm:ss');
	}
	
	// get file name from file path
	function getFileName(filePath) {
		return String(filePath).substring(filePath.lastIndexOf("/") + 1);
	}
	
	// Make alert
	function createAlert(status, tip, message) {
		return '<div class="alert alert-' + status + '"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>' + tip + '! </strong>' + message + '</div>'
	}
	
});